import MyCrypto from "../../MyCrypto";

export interface IUpdateData {
    [index:string]:string
}

interface ICondition {
    KEY:string
    SIGN:string
    VALUE:string
}
/**
 * 记得编码数据,部分存储在数据库中的数据是经过编码的,所以如果那些数据不编码就进行查询就会查不到
 * */
export default class Update{
    private _knex;
    private _crypto = new MyCrypto();
    constructor(props){
        const {knex} = props;
        this._knex = knex;
    }


    /**
     * @param TABLE_NAME 表名
     * @param DATA 要修改的值
     * @param CONDITION where条件
     * */
    update(TABLE_NAME:string, DATA:IUpdateData, CONDITION:ICondition){
        const {KEY, SIGN, VALUE} = CONDITION;
        const _DATA = this.encode(DATA);
        const _VALUE = this.strEncode(VALUE);
        return this._knex(TABLE_NAME).
        where(KEY, SIGN, _VALUE).
        update(_DATA);
    }

    /**
     * @param TABLE_NAME 表名
     * @param DATA 要修改的值
     * @param CONDITION where条件
     * 该函数不对要更新的数据进行编码
     * */
    updateNoneEncodeDATA(TABLE_NAME:string, DATA, CONDITION:ICondition){
        const {KEY, SIGN, VALUE} = CONDITION;
        const _VALUE = this.strEncode(VALUE);
        return this._knex(TABLE_NAME).
        where(KEY, SIGN, _VALUE).
        update(DATA);
    }

    /**
     * @param TABLE_NAME 表名
     * @param DATA {t1:'t1'} 要修改的值
     * @param CONDITION where条件
     * 该函数不对条件的VALUE数据进行编码
     * */
    updateNoneEncodeValue(TABLE_NAME:string, DATA, CONDITION:ICondition){
        const {KEY, SIGN, VALUE} = CONDITION;
        const _DATA = this.encode(DATA);
        return this._knex(TABLE_NAME).
        where(KEY, SIGN, VALUE).
        update(_DATA);
    }

    /**
     * @param TABLE_NAME 表名
     * @param DATA 要修改的值
     * @param CONDITION where条件
     * 该函数不对要更新的数据与条件的VALUE进行编码
     * */
    updateNoneEncodeDATAWithValue(TABLE_NAME:string, DATA, CONDITION:ICondition){
        const {KEY, SIGN, VALUE} = CONDITION;
        return this._knex(TABLE_NAME).
        where(KEY, SIGN, VALUE).
        update(DATA);
    }

    /**
     * 为controller目录下的UpdateAnthology定制的sql,用于批量更新操作
     * @param newAnthology 目标anthology
     * @param oldAnthology 源anthology
     * @param author 作者
     * */
    controllerUpdateAnthology(newAnthology:string, oldAnthology:string, author:string){
        const TABLE_NAME = 'article';
        const _oldAnthology = this.strEncode(oldAnthology);
        const _newAnthology = this.strEncode(newAnthology);
        const KEY = 'anthology';
        const SIGN = '=';
        const VALUE = _oldAnthology;
        return this._knex(TABLE_NAME).where(KEY,SIGN,VALUE).update({anthology:_newAnthology});
    }

    encode(DATA:IUpdateData){
        return this._crypto.dataEncode(DATA);
    }
    strEncode(DATA:string){
        return this._crypto.strEncode(DATA);
    }
}


